package cn.stronglink.assetmanage.utils.dao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.CheckDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;

/**
 * 2为新增入库单，3为未入库，4位入库
 * Author by chencongcong,Date on 2018/9/19
 */
public class CheckDataUtil {
    private static Gson gson = new Gson();
    private static Map<String, Check> orderMap = new HashMap<>();

    //获取所有未入库的数据，根据表单名称去除重复数据
    public static List<Check> getunCheckOrderNoDistince() {
        List<Check> checkList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().distinct()
                .orderDesc(CheckDao.Properties.CreateTime).
                        where(CheckDao.Properties.Status.notEq(Constants.STATUS_FOUR)).
                        orderAsc(CheckDao.Properties.CreateTime).list();
        if (checkList != null) {
            return checkList;
        }
        return null;
    }

    //获取所有入库的数据，根据表单名称去除重复数据
    public static List<Check> getCheckedOrderNoDistince() {
        List<Check> checkList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().distinct()
                .orderDesc(CheckDao.Properties.CreateTime).
                        where(CheckDao.Properties.Status.eq(Constants.STATUS_FOUR)).list();
        if (checkList != null) {
            return checkList;
        }
        return null;
    }

    /**
     * 根据表单号获取表单信息
     *
     * @param orderNo
     * @return
     */
    public static Check getCheckByOrderNo(String orderNo) {
        List<Check> checkList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().
                where(CheckDao.Properties.Id_.eq(orderNo)).list();
        if (checkList != null && checkList.size() > 0) {
            Check check = checkList.get(0);
            if (check != null) {
                return check;
            }
        }
        return null;
    }

    /**
     * 根据表单号获取未入库表单信息
     *
     * @param orderNo
     * @return
     */
    public static Check getUnCheckByOrderNo(String orderNo) {
        List<Check> checkList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().
                where(CheckDao.Properties.Id_.eq(orderNo)).
                where(CheckDao.Properties.Status.notEq(Constants.STATUS_FOUR)).list();
        if (checkList != null && checkList.size() > 0) {
            Check check = checkList.get(0);
            if (check != null) {
                return check;
            }
        }
        return null;
    }

    /**
     * 根据表单号获得该表单中的所有数据
     *
     * @param orderNo
     * @return
     */
    public static List<Asset> getAllAssetByOrderNo(String orderNo) {
        List<Asset> assetList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).list();
        if (assetList != null) {
            return assetList;
        }
        return null;
    }

    /**
     * 根据表单号获得该表单中的未入库数据
     *
     * @param orderNo
     * @return
     */
    public static List<Asset> getunCheckAssetByOrderNo(String orderNo) {
        List<Asset> assetList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).
                where(AssetDao.Properties.Status.notEq(Constants.STATUS_FOUR)).list();
        if (assetList != null) {
            return assetList;
        }
        return null;
    }

    /**
     * 根据表单号获得该表单中的入库数据
     *
     * @param orderNo
     * @return
     */
    public static List<Asset> getUnCheckAssetByOrderNoAndLocation(String orderNo, String location) {
        List<Asset> assetList = null;
        if (Constants.ALL_LOCATION.equals(location)) {
            assetList = getunCheckAssetByOrderNo(orderNo);
        } else {
            assetList = DaoManager.
                    getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                    queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).
                    where(AssetDao.Properties.Status.notEq(Constants.STATUS_FOUR))
                    .where(AssetDao.Properties.RoomName.eq(location)).list();
            if (assetList != null) {
                return assetList;
            }
        }
        return assetList;
    }


    /**
     * 根据表单号获得该表单中的入库数据
     *
     * @param orderNo
     * @return
     */
    public static List<Asset> getCheckAssetByOrderNo(String orderNo) {
        List<Asset> assetList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).
                where(AssetDao.Properties.Status.eq(Constants.STATUS_FOUR)).list();
        if (assetList != null) {
            return assetList;
        }
        return null;
    }

    /**
     * 根据表单号获得该表单中的入库数据
     *
     * @param orderNo
     * @return
     */
    public static List<Asset> getCheckAssetByOrderNoAndLocation(String orderNo, String location) {
        List<Asset> assetList = null;
        if (Constants.ALL_LOCATION.equals(location)) {
            assetList = getCheckAssetByOrderNo(orderNo);
        } else {
            assetList = DaoManager.
                    getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                    queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).
                    where(AssetDao.Properties.Status.eq(Constants.STATUS_FOUR))
                    .where(AssetDao.Properties.RoomName.eq(location)).list();
            if (assetList != null) {
                return assetList;
            }
        }
        return assetList;
    }

    /**
     * @param addOrderNo
     * @return
     */
    public static List<Asset> getAddCheckAssetByOrderNo(String addOrderNo) {
        List<Asset> assetList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.OrderNo.eq(addOrderNo)).list();
        if (assetList != null) {
            return assetList;
        }
        return null;
    }

    /**
     * 根据表单号获得该表单中的所有数据
     *
     * @param assetId
     * @return
     */
    public static Asset getAssetByAssetId(long assetId) {
        List<Asset> assetList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.Asset_id_key.eq(assetId)).list();
        if (assetList != null) {
            return assetList.get(0);
        }
        return null;
    }

    /**
     * 添加表单   2是新加入库单
     *
     * @param check
     */
    public static void addCheckedOrder(Check check) {
        if (check != null) {
            //将单子列表改为已经入库状态
            List<Asset> assetList = getAllAssetByOrderNo(check.getId_());
            check.setAssetList(assetList);
            if (check.getStatus() != Constants.STATUS_FOUR) {
                //不是已入库的单子则是新加的单子
                check.setStatus(Constants.STATUS_ZERO);
            }
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().insertOrReplace(check);
        }
    }

    /**
     * 将表单中所有的资产入库
     *
     * @param check
     */
    public static void saveCheckedOrder(Check check) {
        if (check != null) {
            //将单子列表改为已经入库状态
            List<Asset> assetList = getAllAssetByOrderNo(check.getId_());
            check.setAssetList(assetList);
            check.setStatus(Constants.STATUS_FOUR);
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().insertOrReplace(check);
        }
    }


    /**
     * 将未入库数据修改为已入库数据
     *
     * @param assetList
     */
    public static void saveAssetList(List<Asset> assetList) {
        if (assetList != null) {
            for (int i = 0; i < assetList.size(); i++) {
                Asset asset = assetList.get(i);
                asset.setStatus(Constants.STATUS_FOUR);
                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().insertOrReplace(asset);
            }
        }
    }

    /**
     * 批量插入数据，默认为未入库数据
     *
     * @param assetList
     */
    public static void insertAssetList(List<Asset> assetList) {
        if (assetList != null) {
            for (int i = 0; i < assetList.size(); i++) {
                Asset asset = new Asset();
                asset = saveData(asset, assetList.get(i));
                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().insertOrReplace(asset);
            }
        }
    }

    private static Asset saveData(Asset assetNew, Asset assetOld) {
        assetNew.setOrderNo(assetOld.getOrderNo());
        assetNew.setAssetName(assetOld.getAssetName());
        assetNew.setAssetNo(assetOld.getAssetNo());
        assetNew.setBrandId(assetOld.getBrandId());
        assetNew.setBrandId_(assetOld.getBrandId_());
        assetNew.setBrandName(assetOld.getBrandName());
        assetNew.setCreateBy(assetOld.getCreateBy());
        assetNew.setCreateTime(assetOld.getCreateTime());
        assetNew.setDatacenterId(assetOld.getDatacenterId());
        assetNew.setDatacenterId_(assetOld.getDatacenterId_());
        assetNew.setId(assetOld.getId());
        assetNew.setId_(assetOld.getId_());
        assetNew.setManageBranchId_(assetOld.getManageBranchId_());
        assetNew.setModelId(assetOld.getModelId());
        assetNew.setModelId_(assetOld.getModelId_());
        assetNew.setModelName(assetOld.getModelName());
        assetNew.setPrice(assetOld.getPrice());
        assetNew.setRackId_(assetOld.getRackId_());
        assetNew.setRfidNo(assetOld.getRfidNo());
        assetNew.setRoomId(assetOld.getRoomId());
        assetNew.setRoomId_(assetOld.getRoomId_());
        assetNew.setRoomName(assetOld.getRoomName());
        assetNew.setSerialNo(assetOld.getSerialNo());
        assetNew.setStatus(assetOld.getStatus());
        assetNew.setTypeId(assetOld.getTypeId());
        assetNew.setTypeId_(assetOld.getTypeId_());
        assetNew.setTypeName(assetOld.getTypeName());
        assetNew.setUpdateBy(assetOld.getUpdateBy());
        assetNew.setUpdateTime(assetOld.getUpdateTime());
        assetNew.setUseBranchId_(assetOld.getBrandId_());
        assetNew.setPictureUri(assetOld.getPictureUri());
        assetNew.setIsUpdate(assetOld.getIsUpdate());
        assetNew.setImgPath(assetOld.getImgPath());
        return assetNew;
    }

    public static void saveAsset(Asset asset) {
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().insertOrReplace(asset);
    }


    /**
     * 获取本地数据库所有单子
     */
    public static void getLocalCheckList() {
        List<Check> localCheckList;
        localCheckList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().loadAll();
        if (localCheckList != null && localCheckList.size() > 0) {
            for (int i = 0; i < localCheckList.size(); i++) {
                Check check = localCheckList.get(i);
                orderMap.put(check.getId_(), check);
            }

        }
    }

    /**
     * 保存从服务器获取到的数据
     *
     * @param requestJson
     */
    public static void saveCheckData(String requestJson) {
        Result<List<Check>> checkResult = null;
        checkResult = gson.fromJson(requestJson, new TypeToken<Result<List<Check>>>() {
        }.getType());
        if (checkResult != null && checkResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
            if (checkResult.getData() != null) {
                List<Check> checkList = checkResult.getData();
                // 验收单列表
                if (checkList != null && checkList.size() > 0) {
                    //从服务器获取入库验收数据，成功后，保留本地已经有的单子
                    for (Check check : checkList) {
                        //本地没有的单子才会保存
                        if (!orderMap.containsKey(check.getId_())) {
                            check.setOrderType(Constants.STATUS_THREE);
                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().insert(check);
                            // 获取详情
                            if (check.getAssetList() != null && check.getAssetList().size() > 0) {
                                for (Asset asset : check.getAssetList()) {
                                    asset.setOrderNo(check.getId_());
                                    String base64Str = asset.getImgPath();
                                    if (base64Str != null) {
                                        String pictureUrl = ImageUtils.base64ToFile(base64Str);
                                        if (pictureUrl != null && !"".equals(pictureUrl)) {
                                            asset.setPictureUri(pictureUrl);
                                            asset.setImgPath(ImageUtils.imageToBase64(pictureUrl));
                                        }
                                    }
                                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().insert(asset);
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 删除已经同步的资产数据
     */
    public static void deleteSyncData(List<Check> checkList) {
        if (checkList != null && checkList.size() > 0) {
            for (int i = 0; i < checkList.size(); i++) {
                Check check = checkList.get(i);
                List<Asset> assetList = DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                        getAssetDao().queryBuilder().
                        where(AssetDao.Properties.OrderNo.eq(check.getId_())).list();

                DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                        getAssetDao().deleteInTx(assetList);
            }
            DaoManager.
                    getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().deleteInTx(checkList);
        }

    }

    public static void deleteCheck(Check check) {
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().delete(check);
    }

    public static String updateTime() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currentTime = new Date().getTime();
        String time = sdfDate.format(currentTime);
        return time;
    }

    public static void updateCheck(Check check) {
        if (check != null) {
            //将单子列表改为已经入库状态
            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().insertOrReplace(check);
        }
    }
}
